import { EventEmitter } from "stream";
import { WebSocket } from "ws";
import { ApiMsgEnum, binaryDecode, binaryEncode, IModel } from "../Common";
import { buffer2ArrayBuffer } from "../Utils";
import { MyServer } from "./MyServer";

interface IItem {
    cb: Function;
    ctx: unknown;
}

export class Connection extends EventEmitter {
    private msgMap: Map<ApiMsgEnum, Array<IItem>> = new Map();

    constructor(private server: MyServer, private ws: WebSocket) {
        super()
        this.ws.on("open", () => {

        })
        this.ws.on("close", () => {
            this.emit("close");
        })
        this.ws.on("error", () => { })
        this.ws.on("message", (buffer: Buffer) => {
            try {
                //服务端接收Buffer数据


                //初始字符编码数据
                // const json = strdecode(buffer)
                // const msg = JSON.parse(json)

                //二进制压缩编码数据
                const msg = binaryDecode(buffer2ArrayBuffer(buffer));
                const { name, data } = msg;
                if (this.server.apiMap.has(name)) {
                    try {
                        const cb = this.server.apiMap.get(name)
                        const res = cb.call(null, this, data);
                        this.sendMsg(name, {
                            success: true,
                            res
                        })
                    } catch (e) {
                        this.sendMsg(name, {
                            success: false,
                            error: e.message
                        })
                    }
                } else {
                    try {
                        if (this.msgMap.has(name)) {
                            this.msgMap.get(name).forEach(({ cb, ctx }) => {
                                cb.call(ctx, this, data);
                            });
                        }
                    } catch (error) {
                        console.log(error)
                    }
                }
            } catch (error) {
                console.log(error)
            }
        })
    }

    async sendMsg<T extends keyof IModel['msg']>(name: T, data: IModel['msg'][T]) {
        // await new Promise(res => setTimeout(res, 1000))

        //初始字符编码数据
        // let msg = {
        //     name,
        //     data
        // }
        // const str = JSON.stringify(msg)
        // const typeArray = strencode(str);
        // const buffer = Buffer.from(typeArray)

        //二进制压缩编码数据
        const dataView = binaryEncode(name, data)
        const buffer = Buffer.from(dataView.buffer)

        //服务端发送Buffer数据
        this.ws.send(buffer)
    }

    listenMsg<T extends keyof IModel['msg']>(name: T, cb: (connection: Connection, args: IModel['msg'][T]) => void, ctx: unknown) {
        if (this.msgMap.has(name)) {
            this.msgMap.get(name).push({ cb, ctx });
        } else {
            this.msgMap.set(name, [{ cb, ctx }]);
        }
    }

    unlistenMsg<T extends keyof IModel['msg']>(name: T, cb: (connection: Connection, args: IModel['msg'][T]) => void, ctx: unknown) {
        if (this.msgMap.has(name)) {
            const index = this.msgMap.get(name).findIndex((i) => cb === i.cb && i.ctx === ctx);
            index > -1 && this.msgMap.get(name).splice(index, 1);
        }
    }
}